package com.zerowidth.moc.web.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;

import java.lang.reflect.Type;

public class GsonUtils {

    public static Gson gson = new Gson();

    /**
     * 解析 对象->json字符串
     */
    public static <T> String toJsonString(T t) {
        String jsonString = null;
        try {
            jsonString = gson.toJson(t);
        } catch (Exception e) {

        }
        return jsonString;
    }


    /**
     * 解析 json字符串->对象
     */
    public static <T> T fromJsonStr(String jsonString, Class<T> classOfT) {
        T tResult = null;
        try {
            tResult = gson.fromJson(jsonString, classOfT);
        } catch (Exception e) {

        }
        return tResult;
    }

    public static <T> T fromJsonStr(String jsonString, Type typeOfT) {
        T tResult = null;
        try {
            tResult = gson.fromJson(jsonString, typeOfT);
        } catch (Exception e) {

        }
        return tResult;
    }


    /**
     * 解析json字符串中某指定字段的值
     * <p>
     * 待扩展成通用的 部分解析 功能
     *
     * @param jsonString
     * @param path
     * @return
     */
    public static int getIntFromJson(String jsonString, String path) {
        try {
            JSONObject jsonObject = JSON.parseObject(jsonString);
            int code = jsonObject.getIntValue(path);
            return code;
        } catch (Exception e) {

        }
        return 0;
    }


    public static String getStringFromJson(String jsonString, String path) {
        try {
            JSONObject jsonObject = JSON.parseObject(jsonString);
            String value = jsonObject.getString(path);
            return value;
        } catch (Exception e) {

        }
        return null;
    }
}
